<template>
  <div class="select-input-box" :style="selectStyle">
    <el-input
      v-model="value"
      :placeholder="selectConfig.placeholder || '请输入内容'"
      :clearable="!!selectConfig.clearable"
      @blur="handlerSelectData"
      @clear="handlerSelectData"
      @keyup.native.enter="handlerSelectData"
    >
      <!-- prefix/suffix -->
      <i
        v-if="selectConfig.iconConfig"
        :slot="selectConfig.iconConfig.type"
        :class="['el-input__icon', selectConfig.iconConfig.icon]"
        :style="selectConfig.iconConfig.style || {}"
        @click="clickIcon(selectConfig.iconConfig)"
      />
    </el-input>
  </div>
</template>

<script>
export default {
  name: 'SelectInput',
  props: {
    // 筛选样式
    selectStyle: {
      type: Object,
      default: () => ({})
    },
    // 筛选配置
    selectConfig: {
      type: Object,
      default: () => ({})
    },
    // 筛选数据
    selectData: {
      type: Object,
      default: () => ({})
    },
    // 是否重置
    isReset: {
      type: Boolean,
      default: false
    },
    dynamicSelectData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      value: null
    }
  },
  watch: {
    isReset() {
      this.handlerDefault('init')
    },
    dynamicSelectData: {
      handler(val) {
        if (val && Object.keys(val).length) {
          const { prop } = this.selectData
          for (const key in val) {
            if (Object.hasOwnProperty.call(val, key) && key === prop) {
              this.value = val[key]

              // this.handlerSelectData(this.value, 'init')
            }
          }
        }
      },
      deep: true
    }
  },
  created() {
    this.handlerDefault('init')
  },
  methods: {
    /**
     * 处理默认值
     */
    handlerDefault() {
      const { defaultConfig } = this.selectData
      this.value = null
      if (defaultConfig) {
        this.value = defaultConfig.value
      }
      if (this.value) {
        this.handlerSelectData(this.value, 'init')
      }
    },
    /**
     * 处理筛选
     * @param {*} val 数据
     * @param {*} type 类型
     */
    handlerSelectData(val, type) {
      const { prop } = this.selectData
      const obj = {}
      obj[prop] = this.value
      this.$emit('handlerSelectData', obj, type)
    },
    /**
     * 点击图标
     * @param {*} config 图标配置
     */
    clickIcon(config = {}) {
      if (config.isClick) {
        this.handlerSelectData(this.value)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-input-box {
  width: 132px;

  .el-input {
    width: 100%;
  }
}
</style>
